package com.cloudcc.mobile.view.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import butterknife.Bind;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.EventList.LoginEvent;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.bus.StartWebEvent;
import com.cloudcc.cloudframe.model.UserModel;
import com.cloudcc.cloudframe.util.ConnectivityUtils;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.LoginDBModel;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.LoginPresenter;
import com.cloudcc.mobile.util.AESUtils;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.base.BaseActivity;

/**
 * 用于重新绑定或者登录 系统(在binding失效或者)
 * 
 * <p>
 * #1 当服务器返回的状态码 是-2的时候,打开这个页面进行重新登录 跟wep站点session的添加<br>
 * #2 当wap站点打开到登录页面的时候 就打开该页面
 * <p>
 * 
 * @author seven
 * 
 */
public class BindActivity extends BaseActivity implements IEventLife {

	@Bind(R.id.webview)
	WebView mWebView;
	private WebSettings webSettings;
	private LoginPresenter loginPresenter;
	/**
	 * 当前绑定操作成功还是失败
	 */
	private boolean isBindingSuccess = false;

	@Override
	public void init(Bundle savedInstanceState) {
		super.init(savedInstanceState);
		register();
		initLogin();
	}

	/**
	 * 初始化登录
	 */
	private void initLogin() {

		if (!ConnectivityUtils.hasInternet(mContext)) {
			Tools.showInfo(mContext, getString(R.string.meg_net_no));
			this.finish();
		}

		loginPresenter = new LoginPresenter();
		LoginDBModel login = loginPresenter.getLastLogin();
		if (StringUtils.isBlank(login.userName)
				|| StringUtils.isBlank(login.password)) {
			LogUtils.d(TAG, "用户名密码空" + login.userName + ":" + login.password);
			this.finish();
		}
		// 通过jni获取c代码里面保存的密码 然后解密出来
		String dePassword = AESUtils.getDePassword(login.password);

		if (TextUtils.isEmpty(dePassword)) {// 解密失败
			finish();
			return;
		}
		loginPresenter.login(login.userName, dePassword);
	}

	/**
	 * 根据用户名密码 获取binding
	 * 
	 * @param event
	 */
	public void onEventMainThread(LoginEvent event) {
		LogUtils.d(TAG, "登录:" + event.isOk());
		if (event.isError()) {
			finish();
			return;
		}
		AppContext.binding = event.getData().binding;
		// 保存用户 注意密码
		UserModel user = event.getData().userInfo;
		UserManager.getManager().saveUser(user);
		// wap登录
		loginWebView();
	}

	private void loginWebView() {
		final StartWebEvent webEvent = new StartWebEvent();
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setAllowFileAccess(true);
		webSettings.setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				int end = url.indexOf(";");
				String name;
				if (end != -1) {
					name = url.substring(0, end);
				} else {
					name = url;
				}
				if (name.equals(UrlTools.weixinUrl + UrlTools.loginWeb)
						|| name.equals(UrlTools.weixinUrl + "/main.action")
						|| name.equals(UrlTools.weixinUrl
								+ "/WeiXin_index.action")) {
					isBindingSuccess = true;
					AppContext.islogining = true;
					webEvent.setOk(isBindingSuccess);
					EventEngine.post(webEvent);
					BindActivity.this.finish();
				}
				super.onPageFinished(view, url);
			}

			@Override
			public void onLoadResource(WebView view, String url) {
				super.onLoadResource(view, url);
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
				webEvent.setOk(false);
				EventEngine.post(webEvent);
				BindActivity.this.finish();
			}
		});
		mWebView.loadUrl(UrlManager.getBindingUrl()+ RunTimeManager.getInstance().getServerBinding());
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {// 如果是返回的画 就 让他重新加载 那个页面
			StartWebEvent webEvent = new StartWebEvent();
			webEvent.setOk(false);
			EventEngine.post(webEvent);
			BindActivity.this.finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		unRegister();
		super.onDestroy();
	}

	@Override
	public int getLayoutId() {
		return R.layout.act_bind;
	}

	@Override
	public void register() {
		EventEngine.register(this);
	}

	@Override
	public void unRegister() {
		EventEngine.uregister(this);
	}

}
